CAL_EVENT_COLOR = 'BLUE';
CAL_BDAY_COLOR = 'GREEN';
var loaded = false;

$(document).ready(function () {
    //initialize day view calendar
    $('#calendar-widget').fullCalendar({
        editable: true,
        allDayDefault: false,
        disableDragging: true,
        events: [],
        header: {
            left: 'prev,next today',
            center: '',
            right: ''
        },
        defaultView: 'basicDay',
        dayClick: function (date, allDay) { dayClick(date, allDay); },
        eventClick: function (event) { eventClick(event); }

    });


    // Initialize full month calendar
    $('#calendar').fullCalendar({
        editable: true,
        allDayDefault: false,
        disableDragging: true,
        events: [],
        dayClick: function (date, allDay) { dayClick(date, allDay); },
        eventClick: function (event) { eventClick(event); }
    });


    // Create date-time pickers for the create-event form
    $('#start-time').datetimepicker({
        ampm: true
    });
    $('#end-time').datetimepicker({
        ampm: true
    });
    // Create date-time pickers for the update-event form
    $('#edit-start').datetimepicker({
        ampm: true
    });
    $('#edit-end').datetimepicker({
        ampm: true
    });


    // Setup create button on click
    $('#create-event').click(function () {
        $('#create-event-popup').dialog("open");

    });


    // Submit for new event button in create-event form
    $('#submit-event').click(function () {
        var name = $('#event-name').val();
        var startTime = $('#start-time').val();
        var endTime = $('#end-time').val();

        // alert("Name: " + name + " start: " + startTime + " end: " + endTime);
        createEvent(name, startTime, endTime);
        resetForm();
    });

    $('#update-event').click(function () {

        var name = $('#edit-name').val();
        var startTime = $('#edit-start').val();
        var endTime = $('#edit-end').val();
        var id = $('#edit-id').val();

        updateEvent(name, startTime, endTime, id);
        resetForm();

    });


    $('.cancel-event').click(function () {
        resetForm();
    });



    $("#create-event-popup").dialog();
    $("#create-event-popup").dialog("close");
    $("#edit-event-popup").dialog();
    $("#edit-event-popup").dialog("close");

    $("#error-message-popup").dialog();
    $("#error-message-popup").dialog("close");

    $("#display-event-popup").dialog();
    $("#display-event-popup").dialog("close");

    $("#error-ok").click(function () {
        $("#error-message-popup").dialog("close");
    });


});

function facebookReady() {
    loadCalenadarEvents();
}

function loadCalenadarEvents() {
    if (loaded) { return; }
    loaded = true;
    $(document).ready(function () {
        var accessToken = $("#authToken").val();
        /* Get FB events */
        FB.api('/me/events?access_token=' + accessToken, function (response) {
            myEvents = response;
            var arrayOfEvents = new Array();
            for (var e in myEvents.data) {
                //  console.log("adding: " + myEvents.data[e].id);
                arrayOfEvents[e] = {
                    title: myEvents.data[e].name,
                    start: myEvents.data[e].start_time,
                    end: myEvents.data[e].end_time,
                    id: myEvents.data[e].id,
                    editable: true
                }
            }
            $('#calendar').fullCalendar('addEventSource', arrayOfEvents);
            $('#calendar-widget').fullCalendar('addEventSource', arrayOfEvents);
        });

        /* Get friend's Birthdays */
        FB.api('/me/friends?fields=name,birthday&access_token=' + accessToken, function (response) {
            for (var e in response.data) {
                fRes = response.data[e];
                if (fRes.birthday) {
                    var bDay = Date.parse(fRes.birthday);
                    var nextYear = new Date();
                    nextYear.setFullYear(nextYear.getFullYear() + 1, nextYear.getMonth(), nextYear.getDate());
                    var lastYear = new Date();
                    lastYear.setFullYear(lastYear.getFullYear() - 1, lastYear.getMonth(), lastYear.getDate());
                    bDay.setFullYear(lastYear.getFullYear(), bDay.getMonth(), bDay.getDate());
                    bDay = bDay.getTime();

                    var arrayOfBirthdays = new Array();
                    var i = 0;
                    while (bDay < nextYear) {
                        var bDate = new Date(bDay);
                        //addEvent(fRes.name + "'s Birthday", bDate, bDate, 0, false, CAL_BDAY_COLOR);
                        arrayOfBirthdays[i] = {
                            title: fRes.name + "'s Birthday",
                            start: bDate,
                            end: bDate,
                            id: 0,
                            editable: false,
                            color: CAL_BDAY_COLOR
                        };
                        bDate.setFullYear(bDate.getFullYear() + 1, bDate.getMonth(), bDate.getDate());
                        bDay = bDate.getTime();
                        i++;
                    }
                    $('#calendar').fullCalendar('addEventSource', arrayOfBirthdays);
                    $('#calendar-widget').fullCalendar('addEventSource', arrayOfBirthdays);
                }
            }
        });
    });
}

// Puts event on calendar
function addEvent(title, start, end, id, editable, color) {
    if (!color) { color = CAL_EVENT_COLOR; }
        $('#calendar').fullCalendar('renderEvent', 
                        {
                            title : title,
                            start : start,
                            end   : end,
                            id    : id,
                            editable: editable,
                            color : color
                            
                            
                        },
                        true);
       $('#calendar-widget').fullCalendar('renderEvent',
                        {
                            title: title,
                            start: start,
                            end: end,
                            id: id,
                            editable: editable,
                            color: color


                        },
                        true);
}

// Adds event to Facebook
function createEvent(title, start, end){
    var sDate = Date.parse(start);
    var eDate = Date.parse(end);
    var now = Date.today();


    FB.api('/events', 'post', { name: title, start_time: start, end_time: end }, function (response) {
        console.log("Create Event Response: " + JSON.stringify(response));

        if (!response.error) {
            addEvent(title, start, end, response.id, true);
        }
        else {
            // some other error occured.  Don't add the event to the calendar
            handleResponseError(response);
        }

    });
}

function updateEvent(title, start, end, id) {
    var sDate = Date.parse(start);
    var eDate = Date.parse(end);
    var now = Date.today();


    FB.api('/' + id, 'post', { name: title, start_time: start, end_time: end }, function (response) {
        console.log("Update Event Response: " + JSON.stringify(response));

        if (!response.error) {
            $('#calendar').fullCalendar('removeEvents', id);
            addEvent(title, start, end, id, true);
        }
        else {
            // some other error occured.  Don't add the event to the calendar
            handleResponseError(response);
        }

    });

}

// Clear the form to create an element
function resetForm() {
        // Create event form
        $('#event-name').val("");
        $('#start-time').val("");
        $('#end-time').val("");
        $("#create-event-popup").dialog("close");

        // edit event form
        $('#edit-name').val("");
        $('#edit-start').val("");
        $('#edit-end').val("");
        $('#edit-id').val("");
        $("#edit-event-popup").dialog("close");

        // display event popup
        $('#display-event-popup').dialog("close");

    }

function handleResponseError(response) {
    if (!response.error){ return; }

    var errorCode = response.error.code;
    var message = response.error.message;

    $("#error-text").html(message);
    $("#error-message-popup").dialog();
    

    console.log("Error: " + JSON.stringify(response));
}

function dayClick (date, allDay) {
    resetForm();
    if (date < new Date()) {
        $("#error-text").html("You cannot create new events on a day in the past.");
        $("#error-message-popup").dialog();
        return;
    }
    var dateFormat = 'MM/dd/yyyy hh:mm tt';
    var dateString = $.fullCalendar.formatDate(date, dateFormat);

    // default end date to + 1 hour from the start when clicking on a day 
    var endDate = new Date(date.getTime() + (1 * 60 * 60 * 1000));
    var endDateString = $.fullCalendar.formatDate(endDate, dateFormat);

    if (dateString) {
        dateString = dateString.toString(dateFormat);
    }
    else {
        // Default to today if there was an issue parsing the provided date
        dateString = Date.today().toString(dateFormat);
    }

    $('#create-event-popup').dialog("open");
    $('#start-time').val(dateString);
    $('#end-time').val(endDateString);

}

 function eventClick (event) {
        resetForm();
        // If event isn't editable (birthday) do nothing
        if (!event.editable) { return false; }

        var dateFormat = 'MM/dd/yyyy hh:mm tt';

        //alert("Event ID: " + event.id);
        var start = $.fullCalendar.formatDate(event.start, dateFormat);
        var end = $.fullCalendar.formatDate(event.end, dateFormat);
        var title = event.title;
        var id = event.id;

        // If event has already occured, it cannot be changed
        if (event.end < new Date()) {
            $('#display-start').html(start);
            $('#display-end').html(end);
            $('#display-name').html(title);
            $('#display-event-popup').dialog("open");
            return false;
        }


        $('#edit-event-popup').dialog("open");
        $('#edit-start').val(start);
        $('#edit-end').val(end);
        $('#edit-name').val(title);
        $('#edit-id').val(id);

        // Don't follow URLs
        return false;
}